<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/28 00:40
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Social_Model extends WX_Model
{

    private $userId = '';

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 检查用户是否存在
     * @param $openId
     * @return mixed
     */
    public function checkUserRegist($openId)
    {
        $db = clone($this->db);
        $q = $db->get_where('user_wx', ['openId' => $openId]);
        return $q->row_array();
    }

    /**
     * 通过 openID 获取用户信息
     * @param $openId
     * @param string $fields
     * @return mixed
     * @throws Exception
     */
    public function getUserByOpenId($openId, $fields = '')
    {
        if (empty($fields)) {
            $fields = 'userid, openid, nickname, sex, country, province, city, headimgurl, subscribe';
        }

        try {
            $q = $this->db->select($fields)
                ->from('user_wx')
                ->where('openid', $openId)
                ->limit(1)
                ->get();
            return $q->row_array();
        } catch(PDOException $e) {
            throw new Exception('无法拉取用户信息');
        }
    }

    /**
     * 保存用户信息
     * @param array $userInfo
     * @return bool
     */
    public function saveUserInfo(Array $userInfo)
    {
        try {
            $db = clone($this->db);
            $db->trans_start();

            $date = dateTime();

            $saveUserData = [
                'nickName' => $userInfo['nickname'],
                'lastIp' => remoteAddr(),
                'lastTime' => $date,
                'created' => $date,
                'source' => 'wx',
                'status' => 1
            ];
            $db->insert('user', $saveUserData);
            $userId = $db->insert_id();

            if (empty($userId)) {
                return false;
            }

            $saveUser = clone($this->db);
            $saveUserProfile = [
                'userId' => $userId,
                'avatar' => $userInfo['headimgurl'],
                'bill' => '',
                'trueName' => ''
            ];
            $saveUser->insert('user_profile', $saveUserProfile);

            if(isset($userInfo['tagid_list'])) unset($userInfo['tagid_list']);
            $wxDb = clone($this->db);
            if (!empty($userInfo['subscribe_time'])) {
                $userInfo['subscribe_time'] = date('Y-m-d H:i:s', $userInfo['subscribe_time']);
            }

            $saveWxUser = $userInfo;
            $saveWxUser['userid'] = $userId;
            if (!isset($saveWxUser['unionid'])) {
                $saveWxUser['unionid'] = '';
            }
            $wxDb->insert('user_wx', $saveWxUser);
            $this->userId = $userId;

            if (empty($wxDb->insert_id())) {
                return false;
            }

            @statIncr('wxUsers');

            $db->trans_complete();
            return $db->trans_status();
        } catch(Exception $e) {
            echo 'no access';
        }
        return false;
    }

    /**
     * 获取用户ID
     * @return string
     */
    public function getSaveUserId()
    {
        return $this->userId;
    }

    /**
     * 保存用户关系
     * @param $userId
     * @param $params
     * @return mixed
     */
    public function saveRelationShip($userId, $params)
    {

        $data['userid'] = $userId;
        $data['puserid'] = $params['userId'];

        $db = clone($this->db);
        $q = $db->get_where('user_wx_relationship', ['userid' => $params['userId']]);
        $relationShip = $q->row_array();
        if (!empty($relationShip)) {
            $data['ppuserid'] = intval($relationShip['puserid']);
        }

        $db->insert('user_wx_relationship', $data);
        return $db->insert_id();
    }

    /**
     * 更新最后登录时间
     * @param $openId
     * @return bool
     */
    public function updateLoginTime($openId)
    {
        try {
            $db = clone($this->db);
            $q = $db->get_where('user_wx', array('openid' => $openId));
            $row = $q->row_array();
            if (empty($row)) {
                return false;
            }

            $db->where('openid', $openId);
            $db->update('user_wx', [
                'updated' => dateTime()
            ]);

            $userDb = clone($this->db);
            $q = $userDb->where('id', $row['userid']);
            $q->update('user', [
                'lastIp' => remoteAddr(),
                'lastTime' => dateTime()
            ]);

        } catch(PDOException $e) {}
        return false;
    }

    /**
     * 保存或更新
     * @param array $userInfo
     * @param bool|false $return
     * @return bool
     */
    public function saveUpdate(Array $userInfo, $return = false)
    {
        if (isset($userInfo['tagid_list'])) {
            unset($userInfo['tagid_list']);
        }

        $openid = $userInfo['openid'];

        $db = clone($this->db);
        $q = $db->get_where('user_wx', ['openid' => $openid]);
        $row = $q->row_array();
        $result = null;
        if (!empty($row)) {
            unset($userInfo['openid']);
            if (!empty($userInfo['subscribe_time'])) {
                $userInfo['subscribe_time'] = date('Y-m-d H:i:s', $userInfo['subscribe_time']);
            }
            $userInfo['updated'] = dateTime();
            $db->where('openid', $openid);
            $db->update('user_wx', $userInfo);
            $result = $db->affected_rows();
        } else {
            $result = $this->saveUserInfo($userInfo);
        }

        if ($return) {
            $userWxDb = clone($this->db);
            $q = $userWxDb->get_where('user_wx', ['openid' => $openid]);
            return $q->row_array();
        } else {
            return $result ? true : false;
        }
    }
}